home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / util / gnu / unixcmds.lha / unixcmds / src / grep-2.1 / dfa.h < prev    next >
Encoding:
C/C++ Source or Header  |  1999-10-06  |  14.5 KB  |  370 lines

  1. /* dfa.h - declarations for GNU deterministic regexp compiler
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA */
  17.  
  18. /* Written June, 1988 by Mike Haertel */
  19.  
  20. /* FIXME:
  21.    2.  We should not export so much of the DFA internals.
  22.    In addition to clobbering modularity, we eat up valuable
  23.    name space. */
  24.  
  25. #ifndef PARAMS
  26. # if __STDC__
  27.    typedef void *ptr_t;
  28. #  define PARAMS(x) x
  29. # else
  30.    typedef char *ptr_t;
  31. #  ifndef const
  32. #   define const
  33. #  endif
  34. #  define PARAMS(x) ()
  35. # endif
  36. #endif
  37.  
  38. /* Number of bits in an unsigned char. */
  39. #ifndef CHARBITS
  40. #define CHARBITS 8
  41. #endif
  42.  
  43. /* First integer value that is greater than any character code. */
  44. #define NOTCHAR (1 << CHARBITS)
  45.  
  46. /* INTBITS need not be exact, just a lower bound. */
  47. #ifndef INTBITS
  48. #define INTBITS (CHARBITS * sizeof (int))
  49. #endif
  50.  
  51. /* Number of ints required to hold a bit for every character. */
  52. #define CHARCLASS_INTS ((NOTCHAR + INTBITS - 1) / INTBITS)
  53.  
  54. /* Sets of unsigned characters are stored as bit vectors in arrays of ints. */
  55. typedef int charclass[CHARCLASS_INTS];
  56.  
  57. /* The regexp is parsed into an array of tokens in postfix form.  Some tokens
  58.    are operators and others are terminal symbols.  Most (but not all) of these
  59.    codes are returned by the lexical analyzer. */
  60.  
  61. typedef enum
  62. {
  63.   END = -1,            /* END is a terminal symbol that matches the
  64.                    end of input; any value of END or less in
  65.                    the parse tree is such a symbol.  Accepting
  66.                    states of the DFA are those that would have
  67.                    a transition on END. */
  68.  
  69.   /* Ordinary character values are terminal symbols that match themselves. */
  70.  
  71.   EMPTY = NOTCHAR,        /* EMPTY is a terminal symbol that matches
  72.                    the empty string. */
  73.  
  74.   BACKREF,            /* BACKREF is generated by \<digit>; it
  75.                    it not completely handled.  If the scanner
  76.                    detects a transition on backref, it returns
  77.                    a kind of "semi-success" indicating that
  78.                    the match will have to be verified with
  79.                    a backtracking matcher. */
  80.  
  81.   BEGLINE,            /* BEGLINE is a terminal symbol that matches
  82.                    the empty string if it is at the beginning
  83.                    of a line. */
  84.  
  85.   ENDLINE,            /* ENDLINE is a terminal symbol that matches
  86.                    the empty string if it is at the end of
  87.                    a line. */
  88.  
  89.   BEGWORD,            /* BEGWORD is a terminal symbol that matches
  90.                    the empty string if it is at the beginning
  91.                    of a word. */
  92.  
  93.   ENDWORD,            /* ENDWORD is a terminal symbol that matches
  94.                    the empty string if it is at the end of
  95.                    a word. */
  96.  
  97.   LIMWORD,            /* LIMWORD is a terminal symbol that matches
  98.                    the empty string if it is at the beginning
  99.                    or the end of a word. */
  100.  
  101.   NOTLIMWORD,            /* NOTLIMWORD is a terminal symbol that
  102.                    matches the empty string if it is not at
  103.                    the beginning or end of a word. */
  104.  
  105.   QMARK,            /* QMARK is an operator of one argument that
  106.                    matches zero or one occurences of its
  107.                    argument. */
  108.  
  109.   STAR,                /* STAR is an operator of one argument that
  110.                    matches the Kleene closure (zero or more
  111.                    occurrences) of its argument. */
  112.  
  113.   PLUS,                /* PLUS is an operator of one argument that
  114.                    matches the positive closure (one or more
  115.                    occurrences) of its argument. */
  116.  
  117.   REPMN,            /* REPMN is a lexical token corresponding
  118.                    to the {m,n} construct.  REPMN never
  119.                    appears in the compiled token vector. */
  120.  
  121.   CAT,                /* CAT is an operator of two arguments that
  122.                    matches the concatenation of its
  123.                    arguments.  CAT is never returned by the
  124.                    lexical analyzer. */
  125.  
  126.   OR,                /* OR is an operator of two arguments that
  127.                    matches either of its arguments. */
  128.  
  129.   ORTOP,            /* OR at the toplevel in the parse tree.
  130.                    This is used for a boyer-moore heuristic. */
  131.  
  132.   LPAREN,            /* LPAREN never appears in the parse tree,
  133.                    it is only a lexeme. */
  134.  
  135.   RPAREN,            /* RPAREN never appears in the parse tree. */
  136.  
  137.   CSET                /* CSET and (and any value greater) is a
  138.                    terminal symbol that matches any of a
  139.                    class of characters. */
  140. } token;
  141.  
  142. /* Sets are stored in an array in the compiled dfa; the index of the
  143.    array corresponding to a given set token is given by SET_INDEX(t). */
  144. #define SET_INDEX(t) ((t) - CSET)
  145.  
  146. /* Sometimes characters can only be matched depending on the surrounding
  147.    context.  Such context decisions depend on what the previous character
  148.    was, and the value of the current (lookahead) character.  Context
  149.    dependent constraints are encoded as 8 bit integers.  Each bit that
  150.    is set indicates that the constraint succeeds in the corresponding
  151.    context.
  152.  
  153.    bit 7 - previous and current are newlines
  154.    bit 6 - previous was newline, current isn't
  155.    bit 5 - previous wasn't newline, current is
  156.    bit 4 - neither previous nor current is a newline
  157.    bit 3 - previous and current are word-constituents
  158.    bit 2 - previous was word-constituent, current isn't
  159.    bit 1 - previous wasn't word-constituent, current is
  160.    bit 0 - neither previous nor current is word-constituent
  161.  
  162.    Word-constituent characters are those that satisfy isalnum().
  163.  
  164.    The macro SUCCEEDS_IN_CONTEXT determines whether a a given constraint
  165.    succeeds in a particular context.  Prevn is true if the previous character
  166.    was a newline, currn is true if the lookahead character is a newline.
  167.    Prevl and currl similarly depend upon whether the previous and current
  168.    characters are word-constituent letters. */
  169. #define MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn) \
  170.   ((constraint) & 1 << (((prevn) ? 2 : 0) + ((currn) ? 1 : 0) + 4))
  171. #define MATCHES_LETTER_CONTEXT(constraint, prevl, currl) \
  172.   ((constraint) & 1 << (((prevl) ? 2 : 0) + ((currl) ? 1 : 0)))
  173. #define SUCCEEDS_IN_CONTEXT(constraint, prevn, currn, prevl, currl) \
  174.   (MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn)             \
  175.    && MATCHES_LETTER_CONTEXT(constraint, prevl, currl))
  176.  
  177. /* The following macros give information about what a constraint depends on. */
  178. #define PREV_NEWLINE_DEPENDENT(constraint) \
  179.   (((constraint) & 0xc0) >> 2 != ((constraint) & 0x30))
  180. #define PREV_LETTER_DEPENDENT(constraint) \
  181.   (((constraint) & 0x0c) >> 2 != ((constraint) & 0x03))
  182.  
  183. /* Tokens that match the empty string subject to some constraint actually
  184.    work by applying that constraint to determine what may follow them,
  185.    taking into account what has gone before.  The following values are
  186.    the constraints corresponding to the special tokens previously defined. */
  187. #define NO_CONSTRAINT 0xff
  188. #define BEGLINE_CONSTRAINT 0xcf
  189. #define ENDLINE_CONSTRAINT 0xaf
  190. #define BEGWORD_CONSTRAINT 0xf2
  191. #define ENDWORD_CONSTRAINT 0xf4
  192. #define LIMWORD_CONSTRAINT 0xf6
  193. #define NOTLIMWORD_CONSTRAINT 0xf9
  194.  
  195. /* States of the recognizer correspond to sets of positions in the parse
  196.    tree, together with the constraints under which they may be matched.
  197.    So a position is encoded as an index into the parse tree together with
  198.    a constraint. */
  199. typedef struct
  200. {
  201.   unsigned index;        /* Index into the parse array. */
  202.   unsigned constraint;        /* Constraint for matching this position. */
  203. } position;
  204.  
  205. /* Sets of positions are stored as arrays. */
  206. typedef struct
  207. {
  208.   position *elems;        /* Elements of this position set. */
  209.   int nelem;            /* Number of elements in this set. */
  210. } position_set;
  211.  
  212. /* A state of the dfa consists of a set of positions, some flags,
  213.    and the token value of the lowest-numbered position of the state that
  214.    contains an END token. */
  215. typedef struct
  216. {
  217.   int hash;            /* Hash of the positions of this state. */
  218.   position_set elems;        /* Positions this state could match. */
  219.   char newline;            /* True if previous state matched newline. */
  220.   char letter;            /* True if previous state matched a letter. */
  221.   char backref;            /* True if this state matches a \<digit>. */
  222.   unsigned char constraint;    /* Constraint for this state to accept. */
  223.   int first_end;        /* Token value of the first END in elems. */
  224. } dfa_state;
  225.  
  226. /* Element of a list of strings, at least one of which is known to
  227.    appear in any R.E. matching the DFA. */
  228. struct dfamust
  229. {
  230.   int exact;
  231.   char *must;
  232.   struct dfamust *next;
  233. };
  234.  
  235. /* A compiled regular expression. */
  236. struct dfa
  237. {
  238.   /* Stuff built by the scanner. */
  239.   charclass *charclasses;    /* Array of character sets for CSET tokens. */
  240.   int cindex;            /* Index for adding new charclasses. */
  241.   int calloc;            /* Number of charclasses currently allocated. */
  242.  
  243.   /* Stuff built by the parser. */
  244.   token *tokens;        /* Postfix parse array. */
  245.   int tindex;            /* Index for adding new tokens. */
  246.   int talloc;            /* Number of tokens currently allocated. */
  247.   int depth;            /* Depth required of an evaluation stack
  248.                    used for depth-first traversal of the
  249.                    parse tree. */
  250.   int nleaves;            /* Number of leaves on the parse tree. */
  251.   int nregexps;            /* Count of parallel regexps being built
  252.                    with dfaparse(). */
  253.  
  254.   /* Stuff owned by the state builder. */
  255.   dfa_state *states;        /* States of the dfa. */
  256.   int sindex;            /* Index for adding new states. */
  257.   int salloc;            /* Number of states currently allocated. */
  258.  
  259.   /* Stuff built by the structure analyzer. */
  260.   position_set *follows;    /* Array of follow sets, indexed by position
  261.                    index.  The follow of a position is the set
  262.                    of positions containing characters that
  263.                    could conceivably follow a character
  264.                    matching the given position in a string
  265.                    matching the regexp.  Allocated to the
  266.                    maximum possible position index. */
  267.   int searchflag;        /* True if we are supposed to build a searching
  268.                    as opposed to an exact matcher.  A searching
  269.                    matcher finds the first and shortest string
  270.                    matching a regexp anywhere in the buffer,
  271.                    whereas an exact matcher finds the longest
  272.                    string matching, but anchored to the
  273.                    beginning of the buffer. */
  274.  
  275.   /* Stuff owned by the executor. */
  276.   int tralloc;            /* Number of transition tables that have
  277.                    slots so far. */
  278.   int trcount;            /* Number of transition tables that have
  279.                    actually been built. */
  280.   int **trans;            /* Transition tables for states that can
  281.                    never accept.  If the transitions for a
  282.                    state have not yet been computed, or the
  283.                    state could possibly accept, its entry in
  284.                    this table is NULL. */
  285.   int **realtrans;        /* Trans always points to realtrans + 1; this
  286.                    is so trans[-1] can contain NULL. */
  287.   int **fails;            /* Transition tables after failing to accept
  288.                    on a state that potentially could do so. */
  289.   int *success;            /* Table of acceptance conditions used in
  290.                    dfaexec and computed in build_state. */
  291.   int *newlines;        /* Transitions on newlines.  The entry for a
  292.                    newline in any transition table is always
  293.                    -1 so we can count lines without wasting
  294.                    too many cycles.  The transition for a
  295.                    newline is stored separately and handled
  296.                    as a special case.  Newline is also used
  297.                    as a sentinel at the end of the buffer. */
  298.   struct dfamust *musts;    /* List of strings, at least one of which
  299.                    is known to appear in any r.e. matching
  300.                    the dfa. */
  301. };
  302.  
  303. /* Some macros for user access to dfa internals. */
  304.  
  305. /* ACCEPTING returns true if s could possibly be an accepting state of r. */
  306. #define ACCEPTING(s, r) ((r).states[s].constraint)
  307.  
  308. /* ACCEPTS_IN_CONTEXT returns true if the given state accepts in the
  309.    specified context. */
  310. #define ACCEPTS_IN_CONTEXT(prevn, currn, prevl, currl, state, dfa) \
  311.   SUCCEEDS_IN_CONTEXT((dfa).states[state].constraint,           \
  312.                prevn, currn, prevl, currl)
  313.  
  314. /* FIRST_MATCHING_REGEXP returns the index number of the first of parallel
  315.    regexps that a given state could accept.  Parallel regexps are numbered
  316.    starting at 1. */
  317. #define FIRST_MATCHING_REGEXP(state, dfa) (-(dfa).states[state].first_end)
  318.  
  319. /* Entry points. */
  320.  
  321. /* dfasyntax() takes two arguments; the first sets the syntax bits described
  322.    earlier in this file, and the second sets the case-folding flag. */
  323. extern void dfasyntax PARAMS ((reg_syntax_t, int));
  324.  
  325. /* Compile the given string of the given length into the given struct dfa.
  326.    Final argument is a flag specifying whether to build a searching or an
  327.    exact matcher. */
  328. extern void dfacomp PARAMS ((char *, size_t, struct dfa *, int));
  329.  
  330. /* Execute the given struct dfa on the buffer of characters.  The
  331.    first char * points to the beginning, and the second points to the
  332.    first character after the end of the buffer, which must be a writable
  333.    place so a sentinel end-of-buffer marker can be stored there.  The
  334.    second-to-last argument is a flag telling whether to allow newlines to
  335.    be part of a string matching the regexp.  The next-to-last argument,
  336.    if non-NULL, points to a place to increment every time we see a
  337.    newline.  The final argument, if non-NULL, points to a flag that will
  338.    be set if further examination by a backtracking matcher is needed in
  339.    order to verify backreferencing; otherwise the flag will be cleared.
  340.    Returns NULL if no match is found, or a pointer to the first
  341.    character after the first & shortest matching string in the buffer. */
  342. extern char *dfaexec PARAMS ((struct dfa *, char *, char *, int, int *, int *));
  343.  
  344. /* Free the storage held by the components of a struct dfa. */
  345. extern void dfafree PARAMS ((struct dfa *));
  346.  
  347. /* Entry points for people who know what they're doing. */
  348.  
  349. /* Initialize the components of a struct dfa. */
  350. extern void dfainit PARAMS ((struct dfa *));
  351.  
  352. /* Incrementally parse a string of given length into a struct dfa. */
  353. extern void dfaparse PARAMS ((char *, size_t, struct dfa *));
  354.  
  355. /* Analyze a parsed regexp; second argument tells whether to build a searching
  356.    or an exact matcher. */
  357. extern void dfaanalyze PARAMS ((struct dfa *, int));
  358.  
  359. /* Compute, for each possible character, the transitions out of a given
  360.    state, storing them in an array of integers. */
  361. extern void dfastate PARAMS ((int, struct dfa *, int []));
  362.  
  363. /* Error handling. */
  364.  
  365. /* dfaerror() is called by the regexp routines whenever an error occurs.  It
  366.    takes a single argument, a NUL-terminated string describing the error.
  367.    The default dfaerror() prints the error message to stderr and exits.
  368.    The user can provide a different dfafree() if so desired. */
  369. extern void dfaerror PARAMS ((const char *));
  370.